package com.sdp.irrigation.kafka.producer;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class KafkaProducer {

	private KafkaTemplate<String, String> kafkaTemplate;
	
	public KafkaProducer(KafkaTemplate<String, String> kafkaTemplate)
	{
		this.kafkaTemplate = kafkaTemplate;
	}
	
	public KafkaTemplate<String, String> getKafkaTemplate()
	{
		return this.kafkaTemplate;
	}
	
	public void send(String topic, String msg) {
		ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, 0, null, Base64.encode(msg));
		future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable ex) {
            	log.error("kafka sendMessage error, ex = {}, topic = {}, data = {}", ex.getMessage(), topic, msg);
            }

            @Override
            public void onSuccess(SendResult<String, String> result) {
            	//logger.debug("kafka sendMessage success topic = {}, data = {}", topic, msg);
            }
        });
	}
	
}
